<?php

    if (empty($level)) {
        $level = 0;
    }

?>
<ul class="tree level-<?= $level ?>">
    <? foreach ($categories as $category): ?>
    <?php
        $children = $category['CategoryChildren'];
        $hasChildren = !empty($children);
        
        $class = array();
        if ($hasChildren) {
            $class[] = 'sub';
        }
        
        if ($selected_category == $category['Category']['id']) {
            $class[] = "selected";
        }
    ?>
    
    <li value="<?= $category['Category']['id'] ?>"<?= empty($class) ? '' : ' class="'.implode(' ', $class).'"' ?>>
        <?= $this->Html->link($category['Category']['name'], '/admin_pages/index/' . $category['Category']['id'], array(
            'class' => 'label'
        )) ?>
        <? if ($hasChildren): ?>
            <?= $this->element('category_tree', array(
                'categories' => $children,
                'level'      => $level + 1
            )) ?>
        <? endif ?>
    </li>
    <? endforeach ?>
</ul>